<template>
    <view class="chat">
        <scroll-view id="scrollview" :scroll-top="scrollTop" :scroll-y="true" class="scroll-view">
            <!-- 聊天主体 -->
            <view id="msglistview" class="chat-body">
                <!-- 聊天记录 -->
                <view v-for="(item, index) in messages" :key="index">
                    <!-- 自己发的消息 -->
                    <view v-if="item.role === 'user'" class="item self">
                        <!-- 文字内容 -->
                        <view class="content right">
                            <ua-markdown :source="item.content" />
                        </view>
                        <!-- 头像 -->
                        <view class="avatar">
                            <image :src="avatar" style="width: 40px; height: 40px" />
                        </view>
                    </view>
                    <!-- 机器人发的消息 -->
                    <view v-if="item.role === 'assistant'" class="item Ai">
                        <!-- 头像 -->
                        <view class="avatar">
                            <image :src="gptAvatar" style="width: 40px; height: 40px" />
                        </view>
                        <!-- 文字内容 -->
                        <view class="content left">
                            <ua-markdown :source="item.content" :show-line="false" />
                        </view>
                    </view>
                </view>
            </view>
        </scroll-view>
        <!-- 底部消息发送栏 -->
        <!-- 用来占位，防止聊天消息被发送框遮挡 -->
        <view class="chat-bottom">
            <view class="send-msg">
                <view class="uni-textarea">
                    <uni-easyinput
                        v-model="message"
                        maxlength="300"
                        class="uni-mt-5"
                        trim="all"
                        :placeholder="msg"
                    ></uni-easyinput>
                </view>
                <button class="send-btn" @click="handleEnter">
                    <span>发送</span>
                    <uni-icons
                        style="margin-left: 2rpx"
                        type="paperplane-filled"
                        size="20"
                    ></uni-icons>
                </button>
            </view>
        </view>
    </view>
</template>

<script setup lang="ts">
    import { computed, ref } from 'vue';
    import avatar from '@/static/imgs/img.png';
    import gptAvatar from '@/static/imgs/gpt.jpg';
    import { onHide, onShow } from '@dcloudio/uni-app';
    import { getContent } from '@/api/chatgpt';
    import type { MessageContentDto } from '@/types/chatgpt';
    import { useUserStore } from '@/stores';
    onShow(async () => {
        messages.value = [];
        sessionId.value = uni.getStorageSync('sessionId');
        presetContent.value = uni.getStorageSync('preset');
        describe.value = uni.getStorageSync('describe');
        if (sessionId.value)
            await getContent(sessionId.value).then(({ data }) => {
                messages.value = data;
            });
    });
    onHide(() => {
        uni.removeStorageSync('sessionId');
        uni.removeStorageSync('preset');
        uni.removeStorageSync('describe');
    });
    const messages = ref<MessageContentDto[]>([]);
    const scrollTop = ref(0);
    const message = ref('');
    const userStore = useUserStore();
    const sessionId = ref();
    const presetContent = ref();
    const describe = ref();

    const msg = computed(() => {
        console.log(describe.value);
        return describe.value ? describe.value : '请输入内容';
    });

    async function handleEnter() {
        if (!message.value) {
            return;
        }
        //发送信息
        let now: MessageContentDto = {
            role: 'user',
            content: presetContent.value ? presetContent.value + message.value : message.value
        };
        //返回数据
        messages.value.push(now);
        //添加最后一条数据
        messages.value.push({
            role: 'assistant',
            content: ''
        });
        await uni.connectSocket({
            url:
                import.meta.env.VITE_APP_WEBSOCKET_API +
                userStore.profile?.id +
                '/' +
                'THREE_CHAT' +
                '/' +
                (sessionId.value ? sessionId.value : 'none')
        });
        uni.onSocketOpen(() => {
            uni.sendSocketMessage({
                data: JSON.stringify(messages.value.slice(0, messages.value.length - 1))
            });
        });
        uni.onSocketMessage((result) => {
            if (result.data) {
                let parse = JSON.parse(result.data);
                if (parse?.delta?.content)
                    messages.value[messages.value.length - 1].content += parse?.delta?.content;
            }
        });
        uni.onSocketClose(() => {
            console.log('连接关闭');
        });
    }
</script>

<style lang="scss" scoped>
    $chatContentbgc: #c2dcff;
    $sendBtnbgc: #4ab5f5;

    view,
    button,
    text,
    input,
    textarea {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }

    /* 聊天消息 */
    .chat {
        .scroll-view {
            ::-webkit-scrollbar {
                display: none;
                width: 0 !important;
                height: 0 !important;
                -webkit-appearance: none;
                background: transparent;
                color: transparent;
            }

            // background-color: orange;
            background-color: #ffffff;
            .chat-body {
                display: flex;
                flex-direction: column;
                padding-top: 23rpx;
                // background-color:skyblue;

                .self {
                    justify-content: flex-end;
                }
                .item {
                    display: flex;
                    padding: 23rpx 30rpx;
                    // background-color: greenyellow;

                    .right {
                        background-color: $chatContentbgc;
                    }
                    .left {
                        background-color: #f6f6f6;
                    }
                    // 聊天消息的三角形
                    .right::after {
                        position: absolute;
                        display: inline-block;
                        content: '';
                        width: 0;
                        height: 0;
                        left: 100%;
                        top: 10px;
                        border: 12rpx solid transparent;
                        border-left: 12rpx solid $chatContentbgc;
                    }

                    .left::after {
                        position: absolute;
                        display: inline-block;
                        content: '';
                        width: 0;
                        height: 0;
                        top: 10px;
                        right: 100%;
                        border: 12rpx solid transparent;
                        border-right: 12rpx solid #ededed;
                    }

                    .content {
                        position: relative;
                        max-width: 486rpx;
                        border-radius: 8rpx;
                        word-wrap: break-word;
                        padding: 24rpx 24rpx;
                        margin: 0 24rpx;
                        border-radius: 5px;
                        font-size: 32rpx;
                        font-family: PingFang SC;
                        font-weight: 500;
                        color: #333333;
                        line-height: 42rpx;
                    }

                    .avatar {
                        display: flex;
                        justify-content: center;
                        width: 78rpx;
                        height: 78rpx;
                        background: $sendBtnbgc;
                        border-radius: 8rpx;
                        overflow: hidden;

                        image {
                            align-self: center;
                        }
                    }
                }
            }
        }

        /* 底部聊天发送栏 */
        .chat-bottom {
            width: 100%;
            height: 100rpx;
            background: #ffffff;

            .send-msg {
                display: flex;
                align-items: flex-end;
                padding: 7rpx 30rpx;
                width: 100%;
                min-height: 120rpx;
                position: fixed;
                bottom: 0;
                background: #ededed;
            }

            .uni-textarea {
                padding-bottom: 15rpx;
                flex: 1;

                textarea {
                    width: 537rpx;
                    min-height: 75rpx;
                    max-height: 500rpx;
                    background: #ffffff;
                    border-radius: 8rpx;
                    font-size: 32rpx;
                    font-family: PingFang SC;
                    color: #333333;
                    line-height: 43rpx;
                    padding: 5rpx 8rpx;
                }
            }

            .send-btn {
                display: flex;
                align-items: center;
                justify-content: center;
                margin-bottom: 15rpx;
                margin-left: 25rpx;
                width: 128rpx;
                height: 75rpx;
                background: $sendBtnbgc;
                border-radius: 8rpx;
                font-size: 28rpx;
                font-family: PingFang SC;
                font-weight: 500;
                color: #ffffff;
                line-height: 28rpx;
            }
        }
    }
</style>
